<?php

namespace app\model;

use think\helper\Str;
use think\Model;
use think\model\relation\HasOne;

class StationTask extends Model
{
    public function saveTask(): array
    {
        $data = request()->post();
        $that = $this;
        $account = request()->account;
        $data['admin'] = $account->name ?? $account->account ?? '系统';
        $order = date("YmdHis") . Str::random(6, 1);
        $items = array_map(function ($item) use ($that, $data, $order) {
            //判断是否有未执行的任务，有的话就覆盖，没有就新增
            $it = $that->where('proince', $item)->where('state', 0)->find();
            return [
                "proince" => $item,
                "id" => $it->id ?? null,
                "number" => $order,
                "oil_type" => $data['oil_type'],
                "price" => $data['price'],
                "state" => $data['state'],
                "start_type" => 2,
                "start_time" => $data['start_time'],
                "admin" => $data['admin']
            ];
        }, $data['province']);
        $this->saveAll($items);
        return $items;
    }

    public function lst(): array
    {
        $param = request()->param();
        $data = $this->with(['province', 'oil'])->when(!empty($param['proince']),function ($query) use ($param){
            $query->where('proince', $param['proince']);
        })->when(!empty($param['oil_type']),function ($query) use ($param){
            $query->where('oil_type', $param['oil_type']);
        })->when(!empty($param['start_time']),function ($query) use ($param){
            $query->where('start_time','between',[$param['start_time'][0]." 00:00:00", $param['start_time'][1]." 23:59:59"]);
        })->when(isset($param['state']) && $param['state'] >= 0,function ($query) use ($param){
            $query->where('state', $param['state']);
        })->order(['create_time' => 'desc', 'start_time' => 'asc'])->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }


    public function province(): HasOne
    {
        return $this->hasOne(Area::class, 'adcode', 'proince');
    }

    public function oil()
    {
        return $this->hasOne(StationOilNumber::class, 'id', 'oil_type');
    }
}
